import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:sptapp/api/interface/user_api.dart';
import 'package:sptapp/moudle/common_info.dart';

import '../../api/interface/login_api.dart';
import '../../api/request/response_data.dart';
import '../../config/const.dart';
import '../../widget/common_widget.dart';

class MinSecurityEmailCode extends StatefulWidget {
  final Map arguments;
  const MinSecurityEmailCode({super.key, required this.arguments});

  @override
  State<MinSecurityEmailCode> createState() => _MinSecurityEmailCodeState();
}

class _MinSecurityEmailCodeState extends State<MinSecurityEmailCode> {

  String? password;
  bool isDisabled = true;
  bool isDone = false;
  TextEditingController passwordController = TextEditingController();

  Timer? _countdownTimer;
  int _countdownNum = 60;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getMsgCode();
  }

  getIsDone(){
    if( password == null || password!.isEmpty || password!.length<6 ){
      isDone = false;
    }else{
      isDone = true;
    }
    if(mounted){
      setState(() {});
    }
  }

  _login()async{
    Map<String,dynamic> data = {
      'newEmail':widget.arguments['mail'],
      'smscode':password,
    };
    ResponseData res = await UserAPI.updateGmailCodeLogin(data);
    if(res.code == 200){
      getBaseUserInfo((){
        Navigator.of(context).pop();
        Navigator.of(context).pop();
        SmartDialog.show(builder: (ctx){
          return Container(
            width: 600.w,
            decoration: BoxDecoration(
                color: Color(0xff1E1D20),
                borderRadius: BorderRadius.circular(16.w)
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  child: Stack(
                    children: [
                      Container(
                        padding: EdgeInsets.symmetric(vertical: 32.w,horizontal: 48.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('Succeed'.tr,style: TextStyle(
                                color: Colors.white,
                                fontSize: 32.sp,
                                fontWeight: FontWeight.w400
                            ),)
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Container(height: 1.w,color: Color.fromRGBO(255, 255, 255, 0.2),),
                SizedBox(height: 46.w,),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  child: Column(
                    children: [
                      Container(
                        child: Text('Account update completed'.tr,
                          style: TextStyle(
                              color: Color.fromRGBO(255, 255, 255, 1),
                              fontSize: 32.sp,
                              fontWeight: FontWeight.w500
                          ),textAlign: TextAlign.center,),
                        alignment: Alignment.center,
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 64.w,),
                GestureDetector(
                  onTap: (){
                    SmartDialog.dismiss();
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: 500.w,
                    height: 108.w,
                    decoration: BoxDecoration(
                        color: Color(0xff3C55F8),
                        borderRadius: BorderRadius.circular(8.w)
                    ),
                    child: Text('Confirm'.tr,style: TextStyle(
                        color: Colors.white,
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w600
                    ),),
                  ),
                ),
                SizedBox(height: 32.w,)
              ],
            ),
          );
        },clickMaskDismiss: false);
      });
    }
  }

  /// 获取验证码
  void _getMsgCode() async {
    if(_countdownNum<60){
      return;
    }
    Map<String,dynamic> map = {
      'newEmail':widget.arguments['mail']
    };
    showLoading();
    ResponseData res = await UserAPI.getCodeByChangeEmail(map);
    hideLoading();
    if (res.code == 200) {
      _startCountDownTimer();
    }
  }

  /// 开始倒计时
  _startCountDownTimer() {
    if(_countdownTimer != null){
      _countdownTimer?.cancel();
      _countdownTimer = null;
      _countdownNum = 60;
      if(mounted){
        setState(() {});
      }
    }
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownNum > 0) {
          _countdownNum--;
        } else {
          _countdownTimer?.cancel();
          _countdownTimer = null;
          _countdownNum = 60;
        }
      });
    });
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _countdownTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      appBar: myAppBar(context, 'Email'.tr),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 40.w),
        child: GestureDetector(
          onTap: (){
            getIsDone();
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: SingleChildScrollView(
            child: Container(
              height: 1.sh,
              alignment: Alignment.center,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height:40.w,),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          child: Text('We\'ve emailed you a verification code'.tr,style: TextStyle(
                              color: Colors.white,
                              fontSize: 48.sp,
                              fontWeight: FontWeight.w600
                          ),),
                        )
                      ],
                    ),
                  ),
                  SizedBox(height: 100.w,),
                  Container(
                    child: Text(widget.arguments['mail']??'',style: TextStyle(
                        color: Colors.white,
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w400
                    ),),
                  ),
                  SizedBox(height: 32.w,),
                  //密码
                  Container(
                    width: 670.w,
                    padding: EdgeInsets.symmetric(horizontal: 0.w),
                    child:  Stack(
                      children: [
                        Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              ),
                              Container(
                                width: 92.w,
                                height: 92.w,
                                decoration: BoxDecoration(
                                    border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 2.w),
                                    borderRadius: BorderRadius.circular(8.w)
                                ),
                              )
                            ],
                          ),
                        ),
                        Container(
                          width: 670.w,
                          height: 92.w,
                          child: PinCodeTextField(
                            length: 6,
                            obscureText: false,
                            animationType: AnimationType.fade,
                            scrollPadding: EdgeInsets.zero,
                            keyboardType: TextInputType.number,
                            pinTheme: PinTheme(
                              shape: PinCodeFieldShape.box,
                              borderRadius: BorderRadius.circular(6.w),
                              fieldHeight: 92.w,
                              fieldWidth: 92.w,
                              borderWidth: 2.w,
                              inactiveFillColor: Colors.transparent,
                              inactiveColor: Colors.transparent,
                              activeColor: Colors.transparent,
                              activeFillColor: Colors.transparent,
                              selectedColor: Colors.transparent,
                              selectedFillColor: Colors.transparent,
                              fieldOuterPadding: EdgeInsets.zero,
                              activeBorderWidth: 0.w,
                              inactiveBorderWidth: 0.w,
                              disabledColor: Colors.transparent,
                              selectedBorderWidth: 0.w,
                            ),
                            animationDuration: Duration.zero,
                            enableActiveFill: false,
                            enablePinAutofill: true,
                            textStyle: TextStyle(
                                color: Colors.white,
                                fontSize: 38.sp,
                                fontWeight: FontWeight.w400
                            ),
                            // backgroundColor: Colors.yellow,
                            controller: passwordController,
                            onCompleted: (v) {
                              _login();
                            },
                            onChanged: (value) {
                              setState(() {
                                password = value;
                              });
                              getIsDone();
                            },
                            beforeTextPaste: (text) {
                              //if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
                              //but you can show anything you want here, like your pop up saying wrong paste format or etc
                              return true;
                            }, appContext: context,
                          ),
                        ),


                      ],
                    ),
                  ),
                  SizedBox(height: 32.w,),
                  GestureDetector(
                    onTap: (){
                      FocusScope.of(context).requestFocus(FocusNode());
                      _getMsgCode();
                    },
                    child: Container(
                      alignment: Alignment.centerRight,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Text('Resend'.tr,style: TextStyle(
                              color: Color(0xff666666),
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),
                          SizedBox(width: 10.w,),
                          Visibility(child: Text('${_countdownNum}s',style: TextStyle(
                              color: Colors.white,
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),visible: _countdownNum<60,)
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 64.w,),
                  SizedBox(height: ScreenUtil().bottomBarHeight > 0? ScreenUtil().bottomBarHeight+20.w:48.w,),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

}
